//
//  MPCAlertView.m
//  Pods
//
//  Created by 龙鹏飞 on MPCAlertView_Gap3MPCAlertView_Gap1/9/19.
//
//

#import "MPCAlertView.h"
#import "MPToolsHeader.h"
#import <Masonry.h>

#define MPCAlertView_TitleFont [UIFont YXRegularFontOdSize:20]
#define MPCAlertView_MessageFont [UIFont YXFontOfSize:14]
#define MPCAlertView_ButtonFont [UIFont YXFontOfSize:18]

#define MPCAlertView_titleColor [UIColor YXColorWithHexCode:@"#24242C"]
#define MPCAlertView_messageColor [UIColor YXColorWithHexCode:@"#97979C"]
#define MPCAlertView_textColor [UIColor YXColorWithHexCode:@"#5495FF"]
#define MPCAlertView_Width (MIN(SCREEN_SIZE.width, SCREEN_SIZE.height)-48*2)
#define MPCAlertView_TextWidth (MIN(SCREEN_SIZE.width, SCREEN_SIZE.height)-48*2-30*2)
#define MPCAlertView_OtherButtonBackgroundColor [UIColor YXColorWithHexCode:@"#FFFFFF"]
#define MPCAlertView_CancelButtonBackgroundColor [UIColor YXColorWithHexCode:@"#FFFFFF"]
#define MPCAlertView_Gap1 17   //title距离提示框顶部的距离
#define MPCAlertView_Gap2 20   //button距离message的距离
#define MPCAlertView_Gap3 20   //提示框距离屏幕上下的最小距离
#define MPCAlertView_ButtonsMinHeignt 80 //压缩按钮区域时候的按钮区域的最小高度
#define MPCAlertView_ButtonHeight 44  //每个按钮的高度

@interface MPCAlertViewOtherButtonCell : UITableViewCell

- (void)updateTitle:(NSString *)title Action:(dispatch_block_t)action;

@end

@interface MPCAlertViewCancelButtonCell : UITableViewCell

- (void)updateTitle:(NSString *)title Action:(dispatch_block_t)action;

@end

@interface MPCAlertViewTextView : UITextView

@end

@interface MPCAlertView ()<UITableViewDelegate,UITableViewDataSource,MPCAlertViewDelegate>
{
    UIWindow *_originalWindow; //原始创建的window
    CGFloat _textHeight; //文本的高度
    CGFloat _selectedAreaHeight; //按钮或者tableview的高度
    CGFloat _contentViewHeight;//提示框(白色的高度)
    CGFloat _needCompressText;//是否需要压缩文本 压缩后就出来textview的滚动效果
    CGFloat _needCompressSelectedArea;//是否要压缩按钮选择区域 压缩后就出来tableview的滚动选择
    NSInteger _buttonCount; //按钮的数量或tableview的cell数量
    UIInterfaceOrientation _lastOrientation;//最后的方向
    UIInterfaceOrientation _originalOrientation;//最开始show时候的方向
}

@property (nonatomic, strong) NSString *cancelButtonTitle;
@property (nonatomic, strong) NSMutableArray *otherButtonTitles;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *message;
@property (nonatomic, strong) NSMutableAttributedString *attributedString;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) MPCAlertViewTextView *textView;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *confirmButton;

@property (nonatomic, strong) UIView *containterView;

@property (nonatomic, copy) MPBAlertViewCallBack callBack;


@end

@implementation MPCAlertView

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
{
    if (self = [super init])
    {
        self.cancelButtonTitle = cancelButtonTitle;
        self.title = title;
        self.message = message;
        self.delegate = delegate;
        self.otherButtonTitles = [NSMutableArray array];
        if (otherButtonTitles)
        {
            [self.otherButtonTitles addObject:otherButtonTitles];
            va_list list;
            va_start(list, otherButtonTitles);
            while (1)
            {
                NSString *each = va_arg(list, id);
                if (!each)
                {
                    break;
                }
                [self.otherButtonTitles addObject:each];
            }
            va_end(list);
        }
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
        
        [self configAttributedString];
    }
    return self;
}

- (instancetype _Nullable )initWithTitle:(nullable NSString *)title
                                 message:(nullable NSString *)message
                                callBack:(MPBAlertViewCallBack _Nullable )callBack
                       cancelButtonTitle:(nullable NSString *)cancelButtonTitle
                       otherButtonTitles:(nullable NSString *)otherButtonTitles, ...
{
    if (self = [super init])
    {
        self.cancelButtonTitle = cancelButtonTitle;
        self.title = title;
        self.message = message;
        self.callBack = [callBack copy];
        self.delegate = self;
        self.otherButtonTitles = [NSMutableArray array];
        if (otherButtonTitles)
        {
            [self.otherButtonTitles addObject:otherButtonTitles];
            va_list list;
            va_start(list, otherButtonTitles);
            while (1)
            {
                NSString *each = va_arg(list, id);
                if (!each)
                {
                    break;
                }
                [self.otherButtonTitles addObject:each];
            }
            va_end(list);
        }
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
        
        [self configAttributedString];
    }
    return self;
}

- (void)orientationChanged:(NSNotification *)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:[UIApplication sharedApplication].statusBarOrientationAnimationDuration delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
            UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
            [self rotate:orientation];
        } completion:^(BOOL finished) {
        }];
    });
}

- (void)rotate:(UIInterfaceOrientation) orientation
{
    if (!_lastOrientation)
    {
        return;
    }
    
    if (_lastOrientation == orientation)
    {
        return;
    }
    
    CGFloat difference = [self getAngle:orientation] - [self getAngle:_originalOrientation];
    CGAffineTransform rotation = CGAffineTransformMakeRotation(difference);
    [self.containterView setTransform:rotation];
    
    [self calculate:orientation];
    [self __updateConstraints];
    
}

- (void)__updateConstraints
{
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(_contentViewHeight).priority(900);
    }];
    
    [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(_textHeight);
    }];
    
    switch (_buttonCount)
    {
        case 0:
        {
            
        }
            break;
        case 1:
        {

        }
            break;
        case 2:
        {
        }
            break;
            
        default:
        {
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(MPCAlertView_Width);
                make.height.mas_equalTo(_selectedAreaHeight);
            }];
        }
            break;
    }
    
}

- (void)configAttributedString
{
    NSString *string = [NSString stringWithFormat:@"%@%@%@",MPT_Str_Protect(self.title),(MPT_Str_Is_Valid(self.title)&&MPT_Str_Is_Valid(self.message)?@"\n":@""),MPT_Str_Protect(self.message)];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    if (MPT_Str_Is_Valid(self.title))
    {
        NSRange titleRange = {0,self.title.length};
        [attributedString addAttribute:NSFontAttributeName value:MPCAlertView_TitleFont range:titleRange];
        [attributedString addAttribute:NSForegroundColorAttributeName value:MPCAlertView_titleColor range:titleRange];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.alignment = NSTextAlignmentCenter;
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:titleRange];
    }
    if (MPT_Str_Is_Valid(self.message))
    {
        NSRange messageRange = {string.length-self.message.length,self.message.length};
        [attributedString addAttribute:NSFontAttributeName value:MPCAlertView_MessageFont range:messageRange];
        [attributedString addAttribute:NSForegroundColorAttributeName value:MPCAlertView_messageColor range:messageRange];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.alignment = NSTextAlignmentCenter;
        paragraphStyle.paragraphSpacingBefore = 8;
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:messageRange];
    }
    self.attributedString = attributedString;
}

- (void)calculate:(UIInterfaceOrientation)orientation
{
    _lastOrientation = orientation;
    
    _contentViewHeight = 0;
    _needCompressText = NO;
    _needCompressSelectedArea = NO;
    _textHeight = 0;
    _selectedAreaHeight = 0;
    
    if (self.attributedString)
    {
        self.textView.attributedText = self.attributedString;
        _textHeight = [self.textView sizeThatFits:CGSizeMake(MPCAlertView_TextWidth, MAXFLOAT)].height;
    }
    
    //button的个数
    NSInteger buttonCount = self.otherButtonTitles.count;
    if (MPT_Str_Is_Valid(self.cancelButtonTitle))
    {
        buttonCount ++;
    }
    _buttonCount = buttonCount;
    
    switch (buttonCount)
    {
        case 1:
            _selectedAreaHeight = MPCAlertView_ButtonHeight;
            break;
        case 2:
            _selectedAreaHeight = MPCAlertView_ButtonHeight;
            break;
        default:
        {
            _selectedAreaHeight = (MPCAlertView_ButtonHeight + 2) * buttonCount;
        }
            break;
    }
    
    CGFloat screen_height = SCREEN_SIZE.height;
    
    //文字+按钮高度不够 显示不下
    if (MPCAlertView_Gap1 + _textHeight + MPCAlertView_Gap2 + _selectedAreaHeight > screen_height - MPCAlertView_Gap3 -MPCAlertView_Gap3)
    {
        _contentViewHeight = screen_height - MPCAlertView_Gap3 - MPCAlertView_Gap3;
        
        if (_buttonCount < 3)
        {
            _selectedAreaHeight = MPCAlertView_ButtonHeight;
            if (MPCAlertView_Gap1 + _textHeight + MPCAlertView_Gap2 + MPCAlertView_ButtonHeight > screen_height-MPCAlertView_Gap3-MPCAlertView_Gap3)
            {
                _needCompressText = YES;
                _textHeight = screen_height - MPCAlertView_Gap3 - MPCAlertView_Gap3 - MPCAlertView_ButtonHeight - MPCAlertView_Gap2 - MPCAlertView_Gap1;
            }
        }
        else
        {
            _needCompressSelectedArea = YES;
            //如果固定按钮高度MPCAlertView_ButtonsMinHeignt后 文字+按钮高度还不够
            if (MPCAlertView_Gap1 + _textHeight + MPCAlertView_Gap2 + MPCAlertView_ButtonsMinHeignt > screen_height-MPCAlertView_Gap3-MPCAlertView_Gap3)
            {
                _needCompressText = YES;
                _selectedAreaHeight= MPCAlertView_ButtonsMinHeignt;
                _textHeight = screen_height - MPCAlertView_Gap3 - MPCAlertView_Gap3 - MPCAlertView_ButtonsMinHeignt - MPCAlertView_Gap2 - MPCAlertView_Gap1;
            }
            else
            {
                _selectedAreaHeight = screen_height - MPCAlertView_Gap3 - MPCAlertView_Gap3 - MPCAlertView_Gap2 - _textHeight - MPCAlertView_Gap1;
            }
        }
    }
    else
    {
        _contentViewHeight = MPCAlertView_Gap1 + _textHeight + MPCAlertView_Gap2 + _selectedAreaHeight;
    }
}

- (void)show
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    _originalOrientation = orientation;
    [self calculate:orientation];
    
    _originalWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, MIN(SCREEN_SIZE.width, SCREEN_SIZE.height), MAX(SCREEN_SIZE.width, SCREEN_SIZE.height))];
    _originalWindow.windowLevel = UIWindowLevelAlert;
    
    self.frame = _originalWindow.bounds;
    self.center = _originalWindow.center;
    self.backgroundColor = [UIColor blackColor];
    self.alpha = 0.5;
    
    [_originalWindow addSubview:self];
    [_originalWindow addSubview:self.containterView];
    [self.containterView addSubview:self.contentView];
    
    self.containterView.frame = CGRectMake(0, 0, MAX(SCREEN_SIZE.width, SCREEN_SIZE.height), MAX(SCREEN_SIZE.width, SCREEN_SIZE.height));
    self.containterView.center = _originalWindow.center;
    
    
    [_originalWindow becomeKeyWindow];
    [_originalWindow makeKeyAndVisible];
    
    [self.contentView addSubview:self.textView];
    self.textView.attributedText = self.attributedString;
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.width.mas_equalTo(MPCAlertView_Width);
        make.height.mas_equalTo(_contentViewHeight).priority(900);
        make.centerY.equalTo(self.mas_centerY);
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.contentView.mas_leading).offset(30);
        make.trailing.equalTo(self.contentView.mas_trailing).offset(-30);
        make.top.equalTo(self.contentView.mas_top).offset(MPCAlertView_Gap1);
        make.height.mas_equalTo(_textHeight);
    }];
    
    switch (_buttonCount)
    {
        case 0:
        {
            
        }
            break;
        case 1:
        {
            [self.contentView addSubview:self.cancelButton];
            [self.cancelButton setTitle:MPT_Str_Protect(self.cancelButtonTitle) forState:UIControlStateNormal];
            self.cancelButton.titleLabel.font = MPCAlertView_ButtonFont;
            [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.and.bottom.equalTo(self.contentView);
                make.height.mas_equalTo(MPCAlertView_ButtonHeight);
                make.width.mas_equalTo(MPCAlertView_Width);
            }];
        }
            break;
        case 2:
        {
            [self.contentView addSubview:self.cancelButton];
            [self.cancelButton setTitle:MPT_Str_Protect(self.cancelButtonTitle) forState:UIControlStateNormal];
            self.cancelButton.titleLabel.font = MPCAlertView_ButtonFont;
            [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.and.bottom.equalTo(self.contentView);
                make.height.mas_equalTo(MPCAlertView_ButtonHeight);
                make.width.mas_equalTo(MPCAlertView_Width/2.0);
            }];
            
            [self.contentView addSubview:self.confirmButton];
            NSString *confirmButtonTitle = MPT_Str_Protect(MPT_Ary_GetValidObjectFromArray(self.otherButtonTitles, 0));
            [self.confirmButton setTitle:confirmButtonTitle forState:UIControlStateNormal];
            self.confirmButton.titleLabel.font = MPCAlertView_ButtonFont;
            [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.trailing.and.bottom.equalTo(self.contentView);
                make.height.mas_equalTo(MPCAlertView_ButtonHeight);
                make.width.mas_equalTo(MPCAlertView_Width/2.0);
            }];
        }
            break;
            
        default:
        {
            [self.contentView addSubview:self.tableView];
            [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.and.bottom.equalTo(self.contentView);
                make.width.mas_equalTo(MPCAlertView_Width);
                make.height.mas_equalTo(_selectedAreaHeight);
            }];
        }
            break;
    }
    
    switch (orientation) {
        case UIInterfaceOrientationLandscapeLeft:
        {
            CGAffineTransform rotation = CGAffineTransformMakeRotation(-M_PI/2);
            [self.contentView setTransform:rotation];
        }
            break;
        case UIInterfaceOrientationLandscapeRight:
        {
            CGAffineTransform rotation = CGAffineTransformMakeRotation(M_PI/2);
            [self.contentView setTransform:rotation];
        }
            break;
        case UIDeviceOrientationPortraitUpsideDown:
        {
            CGAffineTransform rotation = CGAffineTransformMakeRotation(M_PI);
            [self.contentView setTransform:rotation];
        }
        case UIDeviceOrientationPortrait:
        {
            CGAffineTransform rotation = CGAffineTransformMakeRotation(0);
            [self.contentView setTransform:rotation];
        }
            break;
        default:
            break;
    }
    
    [self showAnimation:self.contentView orientation:orientation];
}

- (void)showAnimation:(UIView *)view orientation:(UIInterfaceOrientation)orientation
{
    
    if (orientation != UIInterfaceOrientationPortrait)
    {
        return;
    }
    
    CAKeyframeAnimation *sc = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
//    sc.duration = 0.08;
//    sc.removedOnCompletion = NO;
//    sc.fillMode = kCAFillModeForwards;
    NSMutableArray *values = [NSMutableArray array];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.4, 0.4, 1.0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.3, 1.3, 1.0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.4, 0.4, 0.4)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    sc.values = values;
    sc.keyTimes = @[@0,@1];
//    sc.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
//    [view.layer addAnimation:sc forKey:@"sc"];
    
    CABasicAnimation *op = [CABasicAnimation animationWithKeyPath:@"opacity"];
    op.fromValue = @(0);
    op.toValue = @(1);
    op.beginTime = CACurrentMediaTime();
//    op.removedOnCompletion = NO;
//    op.autoreverses = NO;
//    op.duration = 0.08;
//    op.fillMode = kCAFillModeForwards;
//    [view.layer addAnimation:op forKey:@"op"];
    
    CAAnimationGroup *group = [[CAAnimationGroup alloc]init];
    group.animations = @[sc,op];
    group.duration = .2;
    group.removedOnCompletion = NO;
    group.fillMode = kCAFillModeForwards;
    group.autoreverses = NO;
    [view.layer addAnimation:group forKey:@"group"];
    
}

- (void)hide
{
    CGRect rect = self.frame;
    rect.origin.y = 2000;
    self.frame = rect;
    //    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //    [self removeFromSuperview];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _originalWindow = nil;
        [[[[UIApplication sharedApplication] delegate] window] makeKeyWindow];
    });
}

- (CGFloat)getAngle:(UIInterfaceOrientation)orientation
{
    switch (orientation)
    {
        case UIInterfaceOrientationUnknown:
            return 0;
            break;
        case UIInterfaceOrientationPortrait:
            return 0;
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            return M_PI;
            break;
        case UIInterfaceOrientationLandscapeLeft:
            return -M_PI/2;
            break;
        case UIInterfaceOrientationLandscapeRight:
            return M_PI/2;
            break;
        default:
            return 0;
            break;
    }
}

#pragma mark - response methods

- (void)cancelClickedAction:(id)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)])
    {
        [self.delegate alertView:self clickedButtonAtIndex:0];
    }
    [self hide];
}

- (void)confirmClickedAction:(id)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)])
    {
        [self.delegate alertView:self clickedButtonAtIndex:1];
    }
    [self hide];
}

#pragma mark - uitableview delegate / datesource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _buttonCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消的cell 放在最后面
    if (MPT_Str_Is_Valid(self.cancelButtonTitle) && indexPath.row == _buttonCount-1)
    {
        MPCAlertViewCancelButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cancelCell"];
        __weak typeof(self) wSelf = self;
        [cell updateTitle:MPT_Str_Protect(self.cancelButtonTitle) Action:^{
            __strong typeof(wSelf) sSelf = wSelf;
            if (sSelf.delegate && [sSelf.delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)])
            {
                [sSelf.delegate alertView:sSelf clickedButtonAtIndex:0];
            }
            [sSelf hide];
        }];
        return cell;
    }
    //others 的cell
    else
    {
        MPCAlertViewOtherButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"otherCell"];
        __weak typeof(indexPath) wIndexPath = indexPath;
        __weak typeof(self) wSelf = self;
        [cell updateTitle:MPT_Ary_GetValidObjectFromArray(self.otherButtonTitles, indexPath.row) Action:^{
            __strong typeof(wSelf) sSelf = wSelf;
            __strong typeof(wIndexPath) sIndexPath = wIndexPath;
            
            if (sSelf.delegate && [sSelf.delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)])
            {
                [sSelf.delegate alertView:sSelf clickedButtonAtIndex:sIndexPath.row+1];
            }
            [sSelf hide];
        }];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return MPCAlertView_ButtonHeight+2;
}

//TODO:MPCAlertViewDelegate
- (void)alertView:(MPCAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (self.callBack) {
        self.callBack(buttonIndex, alertView);
    }
}

#pragma mark - getters / setters

- (UIView *)contentView
{
    if (!_contentView)
    {
        _contentView = [UIView new];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.cornerRadius = 8;
        _contentView.clipsToBounds = YES;
    }
    return  _contentView;
}

- (UITextView *)textView
{
    if (!_textView)
    {
        _textView = [[MPCAlertViewTextView alloc] init];
        _textView.editable = NO;
//        _textView.backgroundColor = [UIColor redColor];
    }
    return  _textView;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton)
    {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelButton setTitle:@"cancel" forState:UIControlStateNormal];
        [_cancelButton setTitleColor:MPCAlertView_textColor forState:UIControlStateNormal];
        [_cancelButton setTitleColor:[MPCAlertView_textColor colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];
        _cancelButton.titleLabel.font = MPCAlertView_ButtonFont;
        [_cancelButton addTarget:self action:@selector(cancelClickedAction:) forControlEvents:UIControlEventTouchUpInside];
        _cancelButton.backgroundColor = MPCAlertView_CancelButtonBackgroundColor;
        _cancelButton.layer.masksToBounds = YES;
        _cancelButton.layer.borderWidth = 0.5;
        _cancelButton.layer.borderColor = [UIColor YXColorWithHexCode:@"#ededed"].CGColor;
        
    }
    return  _cancelButton;
}

- (UIButton *)confirmButton
{
    if (!_confirmButton)
    {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"confirm" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:MPCAlertView_textColor forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[MPCAlertView_textColor colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];
        _confirmButton.titleLabel.font = MPCAlertView_ButtonFont;
        [_confirmButton addTarget:self action:@selector(confirmClickedAction:) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.backgroundColor = MPCAlertView_OtherButtonBackgroundColor;
        _confirmButton.layer.masksToBounds = YES;
        _confirmButton.layer.borderWidth = 0.5;
        _confirmButton.layer.borderColor = [UIColor YXColorWithHexCode:@"#ededed"].CGColor;
    }
    return _confirmButton;
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[MPCAlertViewOtherButtonCell class] forCellReuseIdentifier:@"otherCell"];
        [_tableView registerClass:[MPCAlertViewCancelButtonCell class] forCellReuseIdentifier:@"cancelCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.bounces = NO;
    }
    return _tableView;
}

- (UIView *)containterView
{
    if (!_containterView)
    {
        _containterView = [[UIView alloc] init];
        _containterView.backgroundColor = [UIColor clearColor];
    }
    return _containterView;
}

@end

@interface MPCAlertViewOtherButtonCell ()

@property (nonatomic, strong) UIButton *button;
@property (nonatomic, copy) dispatch_block_t action;

@end

@implementation MPCAlertViewOtherButtonCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self.contentView addSubview:self.button];
        [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.contentView.mas_leading).offset(10);
            make.trailing.equalTo(self.contentView.mas_trailing).offset(-10);
            make.bottom.equalTo(self.contentView.mas_bottom);
            make.height.mas_equalTo(MPCAlertView_ButtonHeight);
        }];
    }
    return self;
}

- (void)updateTitle:(NSString *)title Action:(dispatch_block_t)action
{
    self.action = action;
    [self.button setTitle:MPT_Str_Protect(title) forState:UIControlStateNormal];
    self.button.titleLabel.font = MPCAlertView_ButtonFont;
}

- (void)buttonAction:(UIButton *)button
{
    if (self.action)
    {
        self.action();
    }
}

- (UIButton *)button
{
    if (!_button)
    {
        _button = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button setTitleColor:MPCAlertView_textColor forState:UIControlStateNormal];
        _button.titleLabel.font = MPCAlertView_ButtonFont;
        _button.layer.masksToBounds = YES;
        _button.layer.cornerRadius = 8;
        _button.backgroundColor = MPCAlertView_OtherButtonBackgroundColor;
        [_button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button;
}

@end

@interface MPCAlertViewCancelButtonCell ()
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, copy) dispatch_block_t action;
@end

@implementation MPCAlertViewCancelButtonCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self.contentView addSubview:self.button];
        [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.contentView.mas_leading).offset(10);
            make.trailing.equalTo(self.contentView.mas_trailing).offset(-10);
            make.bottom.equalTo(self.contentView.mas_bottom);
            make.height.mas_equalTo(MPCAlertView_ButtonHeight);
        }];
    }
    return self;
}

- (void)updateTitle:(NSString *)title Action:(dispatch_block_t)action
{
    self.action = action;
    [self.button setTitle:MPT_Str_Protect(title) forState:UIControlStateNormal];
    self.button.titleLabel.font = MPCAlertView_ButtonFont;
}

- (void)buttonAction:(UIButton *)button
{
    if (self.action)
    {
        self.action();
    }
}

- (UIButton *)button
{
    if (!_button)
    {
        _button = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button setTitleColor:MPCAlertView_textColor forState:UIControlStateNormal];
        _button.titleLabel.font = MPCAlertView_ButtonFont;
        _button.layer.masksToBounds = YES;
        _button.layer.cornerRadius = 8;
        _button.backgroundColor = MPCAlertView_CancelButtonBackgroundColor;
        [_button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button;
}

@end


@implementation MPCAlertViewTextView

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;
{
    if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
    {
        return NO;
    }
    return YES;
}


@end



